package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.Commodity;
import com.home.qh.model.CommodityType;
import com.home.qh.service.CommodityManager;
import com.home.qh.service.CommodityTypeManager;

@Controller
public class CommodityController {
	private transient final Log log = LogFactory.getLog(CommodityController.class);
	private CommodityManager commodityManager;
	private CommodityTypeManager commodityTypeManager;

	@Autowired
	private ApplicationContext context;

	@Autowired
	public void setCommodityManager(CommodityManager commodityManager) {
		this.commodityManager = commodityManager;
	}

	@Autowired
	public void setCommodityTypeManager(CommodityTypeManager commodityTypeManager) {
		this.commodityTypeManager = commodityTypeManager;
	}

	@RequestMapping(value = "/admin/commodityList.*", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView listCities(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'handleRequest' method...");
		}

		Commodity commoditySearch = new Commodity();
		String paramValue = request.getParameter("name");
		String paramCommodityTypeValue = request.getParameter("commodityType");
		if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim())
				&& !"null".equalsIgnoreCase(paramValue)) {
			commoditySearch.setCode(paramValue);
			commoditySearch.setName(paramValue);
		}

		if (paramCommodityTypeValue != null
				&& !"".equalsIgnoreCase(paramCommodityTypeValue.trim())
				&& !"null".equalsIgnoreCase(paramCommodityTypeValue)) {
			Long paramCommodityTypeId = null;
			try {
				paramCommodityTypeId = Long.parseLong(paramCommodityTypeValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramCommodityTypeId != null) {
				CommodityType commodityTypeSearch = new CommodityType();
				commodityTypeSearch.setId(paramCommodityTypeId);
				commoditySearch.setCommodityType(commodityTypeSearch);
			}else{
				commoditySearch.setCommodityType(null);
			}
			

		}

		ModelAndView view = new ModelAndView("admin/commodityList");
		view.addObject("commodityTypeList", commodityTypeManager.getAll());
		view.addObject("commoditySearch", commoditySearch);

		view.addObject("commodityList",	commodityManager.getCommodityByCommodity(commoditySearch, null, false, -1, -1));
		return view;

	}

}
